# -*- coding: utf-8 -*-

import os
import sys
import datetime
import pytz
import jinja2
import time
from openerp import SUPERUSER_ID, models
from openerp.osv import fields
from openerp.osv import orm
from openerp.osv import osv
from openerp.http import request


class CursorProxy():
    def __init__(self):
        pass

    def dictfetchone(self, *args):
        request.cr.execute(*args)
        return request.cr.dictfetchone()

    def dictfetchall(self, *args):
        request.cr.execute(*args)
        return request.cr.dictfetchall()


if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_lodop', "report")

env = jinja2.Environment(loader=loader, autoescape=True)


# jinja2模版自定义过滤器


def strftime(str, fmt):
    dt = datetime.datetime.strptime(str, '%Y-%m-%d')
    dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
    return dt.strftime(fmt.encode('utf-8')).decode('utf-8')

env.filters['strftime'] = strftime

def strfdatetime(str):
    dt = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
    dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
    return dt.strftime('%Y-%m-%d %H:%M:%S'.encode('utf-8')).decode('utf-8')

env.filters['strfdatetime'] = strfdatetime


def getVal(page):
    if page:
        return page.values()[0]
    else:
        return page
env.filters['getVal'] = getVal


def strsplit(long_str, begin, end):
    if isinstance(long_str, str) and len(long_str) >= end <= end:
        return long_str[begin:end]
    else:
        return long_str
env.filters['strsplit'] = strsplit

# jinja2 自定义对象
env.globals['_cr'] = CursorProxy()


# 手工凭证打印扩展（找到相关发票的发票行里的明细根据产品group by进行产品数量合计），调用lodop打印


class account_voucher_lodop(osv.osv):
    _inherit = 'account.voucher'

    def print_voucher_invoice_lodop(self, cr, uid, ids, context=None):
        '''
        找到相关发票的发票行里的明细根据产品group by进行产品数量合计
        '''
        assert len(ids) == 1, 'This option should only be used for a single id at a time'
        return self.pool['report'].get_action(cr, uid, ids, 'report_purchase_invoice', context=context)

    def print_report_product_payment(self, cr, uid, ids, context=None):
        '''打印“供应商付款单产品流水”'''
        assert len(ids) == 1, 'This option should only be used for a single id at a time'
        return self.pool['report'].get_action(cr, uid, ids, 'report_product_payment', context=context)


class report_purchase_invoice(osv.AbstractModel):
    """Model used to embed lodop reports"""
    _name = 'report.report_purchase_invoice'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'account.invoice'
        report_obj = self.pool[model]
        purchase_invoice = self.pool.get("purchase.invoice").browse(cr, uid, ids, context=context)
        account_invoice_all = report_obj.search(cr, uid, [('id', 'in', [account_invoice.id
                                                                        for account_invoice in purchase_invoice.account_invoice_ids if account_invoice.state != 'cancel'])], context=context)
        dict_product = {}
        account_invoice_all_obj = report_obj.browse(cr, uid, account_invoice_all, context=context)
        template = env.get_template("purchase_invoice_print.html")

        return template.render({
            'account_invoice_all': account_invoice_all_obj,
            'purchase_invoice': purchase_invoice,
        })


class report_product_payment(osv.AbstractModel):
    """Model used to embed lodop reports"""
    _name = 'report.report_product_payment'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'account.invoice'
        report_obj = self.pool[model]
        partner_list = []
        amount_total = 0
        account_invoices = report_obj.browse(cr, uid, ids, context=context)
        for account_invoice in account_invoices:
            partner_list.append(account_invoice.partner_id.id)
            amount_total += account_invoice.amount_total
        if len(set(partner_list)) != 1:
            raise osv.except_osv(u'错误', u"只能打印同一供应商发票!")
        template = env.get_template("account_voucher_print.html")
        return template.render({
            'account_invoices': account_invoices,
            'amount_total': amount_total
        })


class account_move_line_print(osv.AbstractModel):
    """Model used to embed lodop reports"""
    _name = 'report.account_move_line_print'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'account.move.line'
        reconcile_obj = self.pool.get('account.move.reconcile')
        report_obj = self.pool[model]
        account_move_lines = report_obj.browse(cr, uid, ids, context=context)
        template = env.get_template("account_move_line_print.html")
        page_journal = {}
        for line in account_move_lines:
            page_journal.setdefault(line.move_id.id, []).append(line)
        for key, val in page_journal.iteritems():
            add_move_line = []
            for line in val:
                if line.partner_id.employee:
                    reconcile_id = reconcile_obj.search(cr, uid, [('name', '=', line.reconcile_ref)], context=context)
                    reconcile_row = reconcile_obj.browse(cr, uid, reconcile_id, context=context)
                    for reconcile_line in reconcile_row.line_id:
                        if reconcile_line.id != line.id:
                           [add_move_line.append(move_line) for move_line in reconcile_line.move_id.line_id if move_line not in add_move_line]
            val.extend(add_move_line)
        users_row = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        print_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        return template.render({
            'all_page': page_journal.values(),
            'print_date': print_date,
            'user_id': users_row.name
        })
